package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author msjykf*{"batch_id":"","template_id":"","requesttype": 1}* batch_id：批次号;template_id:短信模板ID;requesttype:请求类型 1定时任务调度 2动态页面调度
 *
 */
public class SmsCreate implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(SmsCreate.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        try {
            def jsonbody = Util.getRequestBody(request, 'utf-8'); //获取报文
            if (jsonbody.equals("")) {
                return "{\"msg\": \"未获取到入参报文！\",\"code\": -2}"
            };
            JSONObject obj = JSONObject.fromObject(jsonbody); //解析报文
            def batch_id = Util.filterForObject(obj.get("batch_id")); //批次号
            if (batch_id.equals("")) {
                return "{\"msg\": \"批次号不能为空！\",\"code\": -2}"
            };
            def sms_id = Util.filterForObject(obj.get("template_id")); //模板id
            if (sms_id.equals("")) {
                return "{\"msg\": \"短信模板ID不能为空！\",\"code\": -2}"
            };
            def map = eliteBean.chaxun_sql("select pipe,checktype,checknum,saletype from sms_template_search where sms_id='" + sms_id + "'", "dataSource");
            if (map.size() == 0) {
                return "{\"msg\": \"无效的短信模板！\",\"code\": -2}"
            };
            int i = 0;
            def pipe = map[0].get("pipe"); //通道
            int checkstate = map[0].get("checktype"); //审核状态
            int checknum = map[0].get("checknum"); //审核数量
            def saletype = map[0].get("saletype"); //销售类型
            log.debug("checkstate:" + checkstate + "\n" + "checknum:" + checknum);
            if (saletype.equals("")) {
                saletype = "and saletype=0";
            } else {
                saletype = "and (saletype=0 or saletype =" + saletype + ")";
            };
            if (pipe.equals("1")) {
                //log.debug("梦网营销的通道需要排除掉退订的客户");
                eliteBean.update("delete from sms_send_sync where batch_id='" + batch_id + "' and sk_invpty in (select sk_invpty from sms_unsubscribe)", "dataSource");
            };

            //20190718删除短信归档历史表内一个月之前的数据
            eliteBean.update("delete from sms_send_sync_his Where createdate<=Sysdate-31", "dataSource");

            //短信号码去重处理
            log.debug("短信号码去重处理1sms_id:" + sms_id);
            map = eliteBean.chaxun_sql("select se.sms_distinct from sms_template st  left join sms_template se on se.sms_id = st.relation_id where st.sms_id = '" + sms_id + "'", "dataSource")
            def sms_distinct = map[0].get("sms_distinct")
            log.debug("短信号码去重处理2sms_distinct:" + sms_distinct);
            if (sms_distinct == 1) {
                map = eliteBean.chaxun_sql("select mobile_phone,max(rec_guid) as rec_guid,sms_content,count(*) from sms_send_sync where batch_id='" + batch_id + "' group by mobile_phone,sms_content having(count(*))>1", "dataSource");
                log.debug("短信号码去重处理3map.size():" + map.size());
                for (i = 0; i < map.size(); i++) {
                    //20190718短信号码去重归档历史表
                    eliteBean.update("insert into sms_send_sync_his select * from sms_send_sync where batch_id='" + batch_id + "' and mobile_phone='" + map[i].get("mobile_phone") + "' and rec_guid<>'" + map[i].get("rec_guid") + "'", "dataSource");
                    //删除中间表的重复号码
                    eliteBean.update("delete from sms_send_sync where batch_id='" + batch_id + "' and mobile_phone='" + map[i].get("mobile_phone") + "' and rec_guid<>'" + map[i].get("rec_guid") + "'", "dataSource");
                };
            };

            //20190718电话号码正则校验
            map = eliteBean.chaxun_sql("select mobile_phone as mobile_phone from sms_send_sync where batch_id='" + batch_id + "'", "dataSource");
            for (i = 0; i < map.size(); i++) {
                if (!isMobile(map[i].get("mobile_phone"))) {
                    //20190718短信号码校验有效性,无效归档历史表
                    eliteBean.update("insert into sms_send_sync_his select * from sms_send_sync where batch_id='" + batch_id + "' and mobile_phone='" + map[i].get("mobile_phone") + "'", "dataSource");
                    //20190718删除无效短信号码
                    eliteBean.update("delete from sms_send_sync where batch_id='" + batch_id + "' and mobile_phone='" + map[i].get("mobile_phone") + "'", "dataSource");
                }
            };

            //20190718短信黑名单数据归档历史表
            eliteBean.update("insert into sms_send_sync_his select * from sms_send_sync where batch_id='" + batch_id + "' and sk_invpty in (select sk_invpty from specialphone where blacktype='SMS' and status=1 and sk_invpty is not null " + saletype + ")", "dataSource");
            //短信黑名单过滤
            eliteBean.update("delete from sms_send_sync where batch_id='" + batch_id + "' and sk_invpty in (select sk_invpty from specialphone where blacktype='SMS' and status=1 and sk_invpty is not null " + saletype + ")", "dataSource");
            map = eliteBean.chaxun_sql("select count(*) as findrows from sms_send_sync where batch_id='" + batch_id + "'", "dataSource");
            int findrows = map[0].get("findrows");
            log.debug("findrows:" + findrows);
            if (checkstate == 1 && findrows >= checknum) {
                log.debug("需要审核");
                checkstate = 1;
            } else {
                checkstate = 0;
            };

            //净值短信稽核	'SMS001','SMS002' 	 条件：包含'%0.0000%' 或者 数量小于4000
            log.debug("sms_id:" + sms_id);
            if (sms_id.equals("SMS001") || sms_id.equals("SMS002")) {
                def mapZero = eliteBean.chaxun_sql("select count(*) as zeronum from sms_send_sync where batch_id='" + batch_id + "' and sms_id in ('SMS001','SMS002') and sms_content like '%0.0000%'", "dataSource");
                int zeronum = mapZero[0].get("zeronum");
                def mapNetValue = eliteBean.chaxun_sql("select count(*) as netValueNum from sms_send_sync where batch_id='" + batch_id + "' and sms_id in ('SMS001','SMS002') ", "dataSource");
                int netValueNum = mapNetValue[0].get("netValueNum");
                if (zeronum > 0 || netValueNum < 4000) {
                    checkstate = 1;
                    log.debug("checkstate:" + checkstate + "\n" + "netValueNum:" + netValueNum + "zeronum:" + zeronum);
                    log.debug("安正推送短信净值内容存在为：0.0000 或者 数量小于4000	 .转人工审核，并推送消息中心");
                };
            };


            String[] data = new String[3];
            data[0] = "insert into sms_send_task(smsno,exno,batch_id,sms_id,sk_invpty,invpty_name,phone,msg,state,createdate) select sms_send_task_seq.nextval,sms_exmno_sequence.nextval,batch_id,sms_id,sk_invpty,invpty_name,mobile_phone,sms_content,0,sysdate from sms_send_sync where batch_id='" + batch_id + "'";
            data[1] = "update sms_send_batch set state=3,checkstate=" + checkstate + ",significance=" + findrows + " where batch_id='" + batch_id + "'";
            data[2] = "delete from sms_send_sync where batch_id='" + batch_id + "'";
            int[] sqlresult = eliteBean.updateBatch(data, "dataSource");
            return "{\"msg\": \"请求接口成功！\",\"code\": 1}"
        } catch (Exception e) {
            log.error("ErrorMessage:", e);
            return "{\"msg\": \"请求接口失败！\",\"code\": -1}"
        }
    }
    //电话号码正则校验20190718
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean isMatch = false;
        String regex2 = '^((\\+?86)|(\\(\\+86\\)))?((13[0-9])|(14[456789])|(15([0-3,5-9]))|(16[2567])|(17[0135678])|(18[0-9]|19[189]))\\d{8}$';
        p = Pattern.compile(regex2);
        m = p.matcher(str);
        isMatch = m.matches();
        return isMatch;
    }
}